<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <div class="search-wrapper">
      <el-form ref="queryFormRef" :model="mqttServerQueryForm" :inline="true">

        <el-form-item>
          <el-button @click="search" type="primary" icon="Search">{{
              $t("common.search")
            }}</el-button>
          <el-button @click="addmqttServerConf" type="primary" icon="Plus">{{
              $t("common.add")
            }}</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 2. 引入通用表单对话框组件 -->
    <CommonFormDialog
        :dialog-title="dialogTitle"
        v-model="dialogVisible"
        :dialog-width="dialogWidth"
        :form-data="mqttServerConfForm"
        :form-rules="mqttServerConfRules"
        :submit-loading="submitLoading"
        @close="close"
        @cancel="cancel"
        @submit="handleFormSubmit"
        @before-close="handleDialogBeforeClose"
        ref="dialogRef"
    >
      <!-- 2.1 自定义表单项（插槽：标签的“名称”和“排序”） -->
      <template #formItems>

        <el-form-item :label="$t('mqttServerConf.mqttServerCnName')" prop="mqttServerCnName">
          <el-input
              v-model="mqttServerConfForm.mqttServerCnName"
              :placeholder="
              $t('common.placeholderInput') + $t('mqttServerConf.mqttServerCnName')
            "
              clearable
              maxLength="50"
          />
        </el-form-item>
        <el-form-item :label="$t('mqttServerConf.mqttServerEnName')" prop="mqttServerEnName">
          <el-input
              v-model="mqttServerConfForm.mqttServerEnName"
              :placeholder="
              $t('common.placeholderInput') + $t('mqttServerConf.mqttServerEnName')
            "
              clearable
              maxLength="50"
          />
        </el-form-item>
        <el-form-item :label="$t('mqttServerConf.mqttServerIp')" prop="mqttServerIp">
          <el-input
              v-model="mqttServerConfForm.mqttServerIp"
              :placeholder="
              $t('common.placeholderInput') + $t('mqttServerConf.mqttServerIp')
            "
              clearable
              maxLength="50"
          />
        </el-form-item>
        <el-form-item :label="$t('mqttServerConf.mqttServerPort')" prop="mqttServerPort">
          <el-input
              v-model="mqttServerConfForm.mqttServerPort"
              :placeholder="
              $t('common.placeholderInput') + $t('mqttServerConf.mqttServerPort')
            "
              clearable
              maxLength="50"
          />
        </el-form-item>
        <el-form-item :label="$t('mqttServerConf.mqttServerAccount')" prop="mqttServerUserAccount">
          <el-input
              v-model="mqttServerConfForm.mqttServerUserAccount"
              :placeholder="
              $t('common.placeholderInput') + $t('mqttServerConf.mqttServerAccount')
            "
              clearable
              maxLength="50"
          />
        </el-form-item>
        <el-form-item :label="$t('mqttServerConf.mqttServerPassword')" prop="mqttServerUserPassword">
          <el-input
              v-model="mqttServerConfForm.mqttServerUserPassword"
              :placeholder="
              $t('common.placeholderInput') + $t('mqttServerConf.mqttServerPassword')
            "
              clearable
              maxLength="50"
          />
        </el-form-item>
        <el-form-item :label="$t('mqttServerConf.mqttServerEnable')" prop="isEnable">
          <el-select
              v-model="mqttServerConfForm.isEnable"
              :placeholder="
              $t('common.placeholderSelect') + $t('mqttServerConf.mqttServerEnable')
            "
              clearable
          >
            <el-option
                v-for="(item, index) in isEnableList"
                :key="index"
                :label="locale ? item.cndesc : item.endesc"
                :value="item.code"
            />
          </el-select>
        </el-form-item>
        <!-- 可扩展：如需其他表单项（如“颜色”“描述”），直接在这里添加 -->
      </template>
    </CommonFormDialog>

    <el-card>
      <el-row>
        <el-col :span="24">
          <el-card
          ><!-- 数据表格 -->
            <el-table
                max-height="600"
                :data="tableData"
                style="width: 100%"
                @selection-change="handleSelectionChange"
            >
              <el-table-column
                  :label="$t('common.sn')"
                  type="index"
                  width="150"
              />
              <el-table-column
                  :label="$t('mqttServerConf.mqttServerCnName')"
                  align="center"
                  prop="mqttServerCnName"
              >
              </el-table-column>
              <el-table-column
                  :label="$t('mqttServerConf.mqttServerEnName')"
                  align="center"
                  prop="mqttServerEnName"
              />
              <el-table-column
                  :label="$t('mqttServerConf.qosLevel')"
                  align="center"
                  prop="qosLevel"
              />
              <el-table-column
                  :label="$t('mqttServerConf.mqttServerIp')"
                  align="center"
                  prop="mqttServerIp"
              />
              <el-table-column
                  :label="$t('mqttServerConf.mqttServerPort')"
                  align="center"
                  prop="mqttServerPort"
              />
              <el-table-column
                  :label="$t('mqttServerConf.mqttServerAccount')"
                  align="center"
                  prop="mqttServerUserAccount"
              />
              <el-table-column
                  :label="$t('mqttServerConf.mqttServerPassword')"
                  align="center"
                  prop="mqttServerUserPassword"
              />
              <el-table-column
                  :label="$t('common.createTime')"
                  align="center"
                  prop="createTime"
              />
              <el-table-column
                  :label="$t('common.updateTime')"
                  align="center"
                  prop="updateTime"
              />
              <el-table-column
                  label="操作"
                  align="center"
                  width="350"
                  fixed="right"
              >
                <template #default="scope">

                  <el-button
                      type="primary"
                      link
                      icon="Edit"
                      @click="updatemqttServerConf(scope.row)"
                  >{{ $t("common.edit") }}</el-button
                  >
                  <el-button
                      type="danger"
                      link
                      icon="Delete"
                      @click="handleDelete(scope.row)"
                  >{{ $t("common.delete") }}</el-button
                  >
                  <!--                  <el-tooltip :content="scope.row.mqttServerConfEnable != 1?$t('common.mqttServerConfDisable'):$t('common.mqttServerConfEnable')"  placement="top">-->
                  <!--                    <el-button-->
                  <!--                        :disabled="scope.row.mqttServerConfEnable != 1"-->
                  <!--                        type="default"-->
                  <!--                        link-->
                  <!--                        icon="View"-->
                  <!--                        @click="handleDetail(scope.row.id)"-->
                  <!--                    >{{ $t("common.detail") }}</el-button-->
                  <!--                    >-->
                  <!--                  </el-tooltip>-->

                </template>
              </el-table-column>
            </el-table>
            <!-- 分页组件 -->
            <div class="pagination-container">
              <el-pagination
                  v-model:current-page="mqttServerQueryForm.pageNum"
                  v-model:page-size="mqttServerQueryForm.pageSize"
                  :page-sizes="[10, 20, 30, 50]"
                  :total="total"
                  :background="true"
                  layout="total, sizes, prev, pager, next, jumper"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
              />
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup>
import {
  getmqttServerConfPageApi,
  getmqttServerConfListApi,
  addmqttServerConfApi,
  updatemqttServerConfApi,
  delmqttServerConfApi
} from "@/api/ems/mqttServerConf/mqttServerConf"
import { getEnumListByType } from "@/api/enums";
import { EmsCommonEnums } from "@/enum/common/EmsCommonEnums"
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox, ElLoading } from "element-plus";
import { useI18n } from "vue-i18n";
import CommonFormDialog from "@/components/Modal/basicModal.vue"; // 引入通用组件
import { reactive, ref, onMounted, onUnmounted } from "vue";
const tableData = ref(); //表格数组
const locale = ref(window.localStorage.getItem("locale") == "zh-CN");
const router = useRouter();
const total = ref(0);
const dialogWidth = ref("600px");
// 1. 对话框状态
const dialogVisible = ref(false); // 对话框是否显示
const isEnableList = ref([]);
const submitLoading = ref(false); // 提交按钮加载状态
const dialogRef = ref(); // 通用对话框组件引用
const { t } = useI18n();
const dialogTitle = ref(); // 对话框标题
// 2. 设备查询表单数据
const mqttServerQueryForm = reactive({
  pageNum: 1,
  pageSize: 10,
});
//获取mqtt服务器配置枚举列表
const getEnumListByTypes = async(type)=>{
  let res = await getEnumListByType({ type: type });
  if(type == EmsCommonEnums.CommonEnable){
    isEnableList.value = res.data;
  }
}
// 2. 设备新增表单数据
const mqttServerConfForm = reactive({
  qosLevel : 1,
  mqttServerCnName: "", // mqtt服务配置名称中文
  mqttServerEnName: "", // mqtt服务配置名称英文
  mqttServerIp: null, //mqtt服务IP
  mqttServerPort: null, //mqtt服务端口号
  mqttServerUserAccount : "", //mqtt服务账号
  mqttServerUserPassword : "", //mqtt服务密码
  isEnable      : null, //mqtt服务是否可用

});
// 3. 标签表单校验规则
const mqttServerConfRules = reactive({
  mqttServerCnName: [
    { required: true, message: t("common.placeholderInput"), trigger: "blur" },
    { max: 50, message: t("common.inputRule"), trigger: "blur" },
  ],
  mqttServerEnName: [
    { required: true, message: t("common.placeholderInput"), trigger: "blur" },
    { max: 50, message: t("common.inputRule"), trigger: "blur" },
  ],
  mqttServerIp: [
    { required: true, message: t("common.placeholderInput"), trigger: "blur" },
    { max: 50, message: t("common.inputRule"), trigger: "blur" },
  ],
  mqttServerPort: [
    { required: true, message: t("common.placeholderInput"), trigger: "blur" },
    { max: 50, message: t("common.inputRule"), trigger: "blur" },
  ],
  mqttServerUserAccount: [
    { required: true, message: t("common.placeholderInput"), trigger: "blur" },
    { max: 50, message: t("common.inputRule"), trigger: "blur" },
  ],
  mqttServerUserPassword: [
    { required: true, message: t("common.placeholderInput"), trigger: "blur" },
    { max: 50, message: t("common.inputRule"), trigger: "blur" },
  ],
  isEnable: [
    { required: true, message: t("common.placeholderSelect"), trigger: "change" }
  ]
});
//
//mqtt通讯协议类别
const mqttServerConfList = ref([]);

//查询
const search = () => {
  getSelectPage();
};

const handleSizeChange = (val) => {
  mqttServerQueryForm.pageSize = val;
  getSelectPage();
};
const handleCurrentChange = (val) => {

  mqttServerQueryForm.pageNum = val;
  getSelectPage();
};

const getSelectPage = () => {
  getmqttServerConfPageApi(mqttServerQueryForm).then((res) => {
    total.value = res.data.total;
    tableData.value = res.data.records;
  });
};
// 关闭对话框时，触发 update:modelValue 事件
const close = () => {
  dialogVisible.value = false; // 通知父组件将 dialogVisible 设为 false
};
// 关闭对话框时，触发 update:modelValue 事件
const cancel = () => {
  dialogVisible.value = false; // 通知父组件将 dialogVisible 设为 false
};
//新增调出弹框
const addmqttServerConf = () => {
  dialogVisible.value = true;
  Object.assign(mqttServerConfForm, {
    id:null,
    qosLevel : 1,
    mqttServerCnName: "", // mqtt服务配置名称中文
    mqttServerEnName: "", // mqtt服务配置名称英文
    mqttServerIp: null, //mqtt服务IP
    mqttServerPort: null, //mqtt服务端口号
    mqttServerUserAccount : "", //mqtt服务账号
    mqttServerUserPassword : "", //mqtt服务密码
    isEnable      : null, //mqtt服务是否可用
  });
  dialogTitle.value = t("mqttServerConf.mqttServerAdd");
};
//修改调出弹框
const mqttServerConfId = ref();
const updatemqttServerConf = (row) => {
  dialogTitle.value = t("mqttServerConf.mqttServerUpdate");
  dialogVisible.value = true;
  mqttServerConfId.value = row.id;
  Object.assign(mqttServerConfForm, row);
};
const handleDialogBeforeClose = () => {
  dialogVisible.value = false; // 通知父组件将 dialogVisible 设为 false
};
//提交数据
const handleFormSubmit = () => {
  if (dialogTitle.value == t("mqttServerConf.mqttServerAdd")) {
    addmqttServerConfApi(mqttServerConfForm).then((res) => {
      if (res.code == 200) {
        ElMessage.success(t("common.success"));
        getSelectPage();
        dialogVisible.value = false;
      } else {
        ElMessage.success(t("common.success"));
      }
    });
  } else {
    updatemqttServerConfApi(Object.assign(mqttServerConfForm)).then((res) => {
      if (res.code == 200) {
        ElMessage.success(t("common.success"));
        getSelectPage();
        dialogVisible.value = false;
      } else {
        ElMessage.success(t("common.success"));
      }
    });
  }
};
//删除数据
const handleDelete = (row) => {
  ElMessageBox.confirm(`是否确认删除`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    delmqttServerConfApi(row.id).then((res) => {
      if (res.code == 200) {
        ElMessage.success(t("common.success"));
        getSelectPage();
      } else {
        ElMessage.success(t("common.error"));
      }
    });
  });
};

onMounted(() => {
  getSelectPage();
  getEnumListByTypes(EmsCommonEnums.CommonEnable);
});
onUnmounted(() => {});
</script>
<style lang="scss" scoped>
:root[data-theme="dark"] {
  .app-container {
    :deep(.el-dialog) {
      .el-form {
        .el-input__wrapper {
          box-shadow: 0 0 0 1px var(--el-border-color) inset;
        }
      }
    }
  }
}
.app-container {
  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }

  :deep(.el-dialog) {
    .el-dialog__body {
      padding: 20px 40px;
    }

    .el-form {
      .el-form-item {
        margin-bottom: 22px;

        &:last-child {
          margin-bottom: 0;
        }

        .el-form-item__label {
          font-weight: 500;
          padding-right: 20px;
        }
      }

      .el-select {
        width: 100%;
      }
    }
  }
}
</style>
